#pragma once 

#ifndef COMTOOLS_H
#define COMTOOLS_H

#include "EXPORT.h"
#include <comdef.h>

class COMTools
{
public:
  static void UnpackVariant(VARIANT val, BSTR * bdata)
  {
    try {
      HRESULT hr;
      BYTE * pData = NULL;
      void HUGEP *pvData;
      hr = SafeArrayAccessData(val.parray, &pvData);
      long cElements = val.parray->rgsabound[0].cElements;
      pData = new BYTE[cElements +2];
      memset(pData, 0, cElements +2);
      memcpy(pData, pvData, cElements);
      hr = SafeArrayUnaccessData(val.parray); 
      BSTR unicodestr = _bstr_t((LPOLESTR)pData).copy(); 
      delete[] pData;

      char *ansistr;
      int lenW = ::SysStringLen(unicodestr);
      int lenA = ::WideCharToMultiByte(CP_ACP, 0, unicodestr, lenW, 0, 0, NULL, NULL);
      if (lenA > 0) {
        ansistr = new char[lenA + 1]; 
        memset(ansistr, 0, lenA + 1);
        ::WideCharToMultiByte(CP_ACP, 0, unicodestr, lenW, ansistr, lenA, NULL, NULL);
        ansistr[lenA] = 0; 
      } 
      ::SysFreeString(unicodestr);     
     
      if (0 < strlen(ansistr)) {
        char* szTemp = new char[strlen(ansistr)+1];
        memset(szTemp, 0, strlen(ansistr)+1);
        strncpy_s(szTemp, strlen(ansistr), &ansistr[1], strlen(ansistr));
        delete[] ansistr;
        (*bdata) = _bstr_t(szTemp).copy();
        delete[] szTemp;
      } else {
        (*bdata) = _bstr_t("").copy();
      }
    } catch (...) {
    }
  }

  static void PackVariant(VARIANT* pVar, char* pBuf, int nBufLen)
  {
     VARIANT var;
     VariantInit(&var);  //Initialize our variant
     var.vt = VT_ARRAY | VT_UI1;

     SAFEARRAYBOUND  rgsabound[1];
     rgsabound[0].cElements = nBufLen;  //
     rgsabound[0].lLbound = 0;
     var.parray = SafeArrayCreate(VT_UI1,1,rgsabound);
     void * pArrayData = NULL;
     SafeArrayAccessData(var.parray,&pArrayData);
     memcpy(pArrayData, pBuf, nBufLen);
     SafeArrayUnaccessData(var.parray);
     *pVar= var;
  }
};

#endif // COMTOOLS_H